/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 分拣模式弹窗
 *  */
import React, { useEffect, useState, useCallback } from 'react';
import { Modal, Form, Select, Input, Row, Col } from 'antd';
import { connect } from 'dva';

const { Option } = Select;

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const canSelectBrand = ['ht', 'jt'];
const disabledSelectBrand = ['zt', 'yt'];

const renderFormItems = ({ token: initialValue = {}, brands = [], brandList, sortingLineType }) => {
  /** 出港类型 */
  const outPort = sortingLineType === '2';
  /** 出港有效的品牌 */
  const enableBrand = brand => ['zt', 'ht', 'yt'].includes(brand);

  /** 中通和百世需要输入分拣线编号 */
  const showInput = brand => ['zt', 'ht'].includes(brand);

  /** 展示上线扫描选择 */
  const showScanType = (brand, type) => {
    // 中通特殊处理
    if (brand === 'zt' && (type === '0' || !type)) {
      return false;
    }
    if (disabledSelectBrand.includes(brand) && (type === '0' || outPort)) {
      return false;
    }
    if (canSelectBrand.includes(brand)) {
      return true;
    }
    return type !== '0';
  };

  const selectType = (fn, isOutPort, brand) => {
    /** 分拣线类型 */
    const typeMap = {
      0: '标准分拣',
      1: '三段码分拣',
      2: '地址分拣',
      12: '三段码优先，地址补充',
      21: '地址优先，三段码补充',
    };
    // 标准分拣品牌
    const standModel = ['jt', 'yt'];
    // 出港只有标准分拣
    if (isOutPort) {
      typeMap[1] = undefined;
      typeMap[2] = undefined;
      typeMap[12] = undefined;
      typeMap[21] = undefined;
    }
    if (!fn(brand) && !standModel.includes(brand)) {
      typeMap[0] = undefined;
    }
    const arr = [];
    Object.keys(typeMap).forEach(key => {
      if (typeMap[key]) {
        arr.push({
          label: typeMap[key],
          value: key,
        });
      }
    });
    return arr;
  };

  const scanSelectType = () => {
    /** 上线扫描类型 */
    const scanType = {
      0: '不上传',
      1: '上传到件',
    };
    const arr = [];
    Object.keys(scanType).forEach(key => {
      if (scanType[key]) {
        arr.push({
          label: scanType[key],
          value: key,
        });
      }
    });
    return arr;
  };
  const formItems = [];

  // 过滤全部品牌和全部格口
  brandList.filter(i => !['0', 'all'].includes(i.brand)).forEach(val => {
    const { brand, name } = val;
    const { type, key, isDao } = initialValue[brand] || {};
    const canSelect = brands.includes(brand);
    // 出港，只显示支持出港的品牌
    if (outPort && !enableBrand(brand)) return;
    formItems.push({
      brand,
      showScanType: showScanType(brand, type),
      showInput: showInput(brand),
      selectLabel: name,
      optionsArr: selectType(outPort ? enableBrand : showInput, outPort, brand),
      scanOptions: scanSelectType(),
      inputLabel: showInput(brand) && `${name}分拣线编号`,
      initialSelectValue: type || ((outPort ? enableBrand(brand) : showInput(brand)) ? '0' : '1'),
      initialInputValue: key || undefined,
      initialScanType: isDao || '1', // 上线扫描类型
      canSelect,
    });
  });
  return formItems;
};

const SortingModelModal = ({ visible, record, form, handleSubmit, onCancel, sortLineBrands }) => {
  const { getFieldDecorator, validateFields, isFieldsTouched } = form;
  const {
    brand = '',
    sorting_line_token: sortLineToken = '',
    id,
    sorting_line_type: sortLineType,
  } = record;

  const [tokenVal, setTokenVal] = useState({});
  const [brands, setBrands] = useState([]);

  const getFormValues = (selectBrands = []) => {
    let sortingLineToken = {};
    validateFields((err, values) => {
      if (err || !isFieldsTouched()) return;
      const formValues = {};
      Object.keys(values).forEach(key => {
        const [brandName] = key.split('_');
        // 只有被选中的品牌才能修改数据
        if (selectBrands.includes(brandName)) {
          formValues[brandName] = {
            type: values[brandName],
            key: values[`${brandName}_key`],
            isDao: values[`${brandName}_isDao`],
          };
          if (['zt', 'yt'].includes(brandName) && formValues[brandName].type === '0') {
            delete formValues[brandName].isDao;
          }
        }
      });
      sortingLineToken = formValues;
    });
    return sortingLineToken;
  };

  const onOk = useCallback(
    (submitId, selectBrands) => {
      const formValuesString = JSON.stringify(getFormValues(selectBrands));
      if (handleSubmit) {
        if (formValuesString === '{}') {
          onCancel();
          return;
        }
        handleSubmit({ sorting_line_token: formValuesString, id: submitId });
      }
      if (onCancel) {
        onCancel();
      }
    },
    [handleSubmit, isFieldsTouched, onCancel, validateFields],
  );

  /**
   * 分拣类型选择
   *  */
  const onSelectChange = () => {
    const formValues = getFormValues(brands);
    // 更新fromItem
    setTokenVal(formValues);
  };

  useEffect(
    () => {
      if (visible) {
        if (brand) {
          setBrands(brand.split(','));
        }
        if (sortLineToken) {
          let token = {};
          try {
            token = JSON.parse(sortLineToken);
          } catch (error) {
            console.log('json字符串不完整');
          }
          setTokenVal(token);
        }
      } else {
        setBrands([]);
        setTokenVal({});
      }
    },
    [visible, brand, sortLineToken],
  );

  return (
    <Modal
      destroyOnClose
      title="分拣模式"
      visible={visible}
      onOk={() => onOk(id, brands)}
      onCancel={onCancel}
      width={800}
    >
      <Form {...formItemLayout}>
        {renderFormItems({
          token: tokenVal,
          brands,
          brandList: sortLineBrands,
          sortingLineType: sortLineType,
        }).map(val => (
          <Row key={val.brand} type="flex">
            <Col span={6}>
              <FormItem label={val.selectLabel}>
                {getFieldDecorator(val.brand, {
                  initialValue: val.initialSelectValue,
                })(
                  <Select
                    style={{ width: 180 }}
                    onSelect={onSelectChange}
                    disabled={!val.canSelect}
                  >
                    {val.optionsArr.map(({ value, label }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="上线扫描" labelCol={{ span: 11 }} wrapperCol={{ span: 13 }}>
                {getFieldDecorator(`${val.brand}_isDao`, {
                  initialValue: val.initialScanType,
                })(
                  <Select disabled={!val.canSelect || !val.showScanType}>
                    {val.scanOptions.map(({ value, label }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </FormItem>
            </Col>
            {val.showInput && (
              <Col span={10}>
                <FormItem label={val.inputLabel} labelCol={{ span: 9 }} wrapperCol={{ span: 13 }}>
                  {getFieldDecorator(`${val.brand}_key`, {
                    initialValue: val.initialInputValue,
                    rules: [
                      {
                        max: 40,
                        message: '名称最长不超过40位字符',
                      },
                    ],
                  })(
                    <Input
                      disabled={!val.canSelect}
                      placeholder={`请输入${val.selectLabel}分拣线编号`}
                    />,
                  )}
                </FormItem>
              </Col>
            )}
          </Row>
        ))}
      </Form>
    </Modal>
  );
};

export default Form.create()(
  connect(({ automatic }) => ({ sortLineBrands: automatic.sortLineBrands }))(SortingModelModal),
);
